package com.qingyun.pdfservice.config;

import com.qingyun.common.dto.UserDTO;
import com.qingyun.common.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息拦截器 - 从请求头中提取用户信息并填充到UserHolder
 */
@Slf4j
@Component
class UserInfoInterceptor implements HandlerInterceptor {

    @Autowired
    private UserHolder userHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 从请求头中获取用户信息
            String userIdStr = request.getHeader("X-User-Id");
            String userName = request.getHeader("X-User-Name");
            String userPermissionStr = request.getHeader("X-User-Permission");

            log.debug("从请求头获取用户信息 - UserId: {}, UserName: {}, Permission: {}", 
                     userIdStr, userName, userPermissionStr);

            if (userIdStr != null && !userIdStr.trim().isEmpty()) {
                // 构建UserDTO对象
                UserDTO userDTO = new UserDTO();
                userDTO.setId(Long.parseLong(userIdStr));
                userDTO.setNickName(userName);
                
                if (userPermissionStr != null && !userPermissionStr.trim().isEmpty()) {
                    try {
                        userDTO.setPermission(Long.parseLong(userPermissionStr));
                    } catch (NumberFormatException e) {
                        log.warn("用户权限格式错误: {}", userPermissionStr);
                        userDTO.setPermission(0L); // 默认权限
                    }
                }

                // 设置到UserHolder中
                userHolder.set(userDTO);
                log.debug("用户信息已设置到UserHolder: {}", userDTO);
            } else {
                log.warn("请求头中未找到X-User-Id，用户信息未设置");
            }
        } catch (Exception e) {
            log.error("处理用户信息时发生错误", e);
        }

        return true; // 继续执行
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal中的用户信息，避免线程复用导致脏数据
        try {
            userHolder.clear();
            log.debug("用户信息已从UserHolder中清理");
        } catch (Exception e) {
            log.error("清理用户信息时发生错误", e);
        }
    }
}

